package com.rkc.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.rkc.enums.BizCodeEnum;
import com.rkc.utils.CommonUtil;
import com.rkc.utils.JsonData;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author `RKC`
 * @date 2022/3/12 16:01
 */
@Component
public class SentinelBlockHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        JsonData res = null;
        if (e instanceof FlowException) {
            res = JsonData.buildResult(BizCodeEnum.CONTROL_FLOW);
        } else if (e instanceof DegradeException) {
            res = JsonData.buildResult(BizCodeEnum.CONTROL_DEGRADE);
        } else if (e instanceof AuthorityException) {
            res = JsonData.buildResult(BizCodeEnum.CONTROL_AUTH);
        }
        response.setStatus(200);
        if (res != null) {
            CommonUtil.sendJsonMessage(response, res);
        }
    }
}
